package com.atguigu.lease.common.exception;

import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;


import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 处理所有控制器抛出的异常，返回统一的JSON格式
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Resource
    private Environment environment;

    @ExceptionHandler(LeaseException.class)
    public ResponseEntity<Result<?>> handleLeaseException(LeaseException e, HttpServletRequest request) {
        log.warn("业务异常: URL={}, Code={}, Message={}",
                request.getRequestURI(), e.getCode(), e.getMessage());

        Result<?> result = Result.build(null,
                ResultCodeEnum.valueOfCode(e.getCode()).orElse(ResultCodeEnum.FAIL));
        return new ResponseEntity<>(result, HttpStatus.OK);
    }




}